package com.zhong.reflect;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhong.model.User;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 *  反射--字段
 * @author:yanglin on 2018/6/17.
 */
public class FieldDemo {

    /** 返回Field数组，只能是public */
    @Test
    public void demo1(){
        Class<User> clazz = User.class;
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.err.println(field.getName());
        }
    }

    /** 返回Field数组，所有的 */
    @Test
    public void demo2(){
        Class<User> clazz = User.class;
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            System.err.println(field.getName());
        }
    }

    @Test
    public void demo3() throws NoSuchFieldException {
        Class<User> clazz = User.class;
        Field name = clazz.getField("sale");
        System.err.println(name.getName());
    }

    @Test
    public void demo4(){
        Class<User> clazz = User.class;
        Class<? super User> superclass = clazz.getSuperclass();
        ArrayList<Field> fields = Lists.newArrayList();
        while (superclass != null) {
            Field[] declaredFields = superclass.getDeclaredFields();
            for (Field field : declaredFields) {
                fields.add(field);
            }
            superclass = superclass.getSuperclass();
        }
        for (Field field : fields) {
            System.err.println(field.getName());
        }
    }
}
